//
//  HRBaseRequstDataModel.m
//  Hear
//
//  Created by mac on 2017/3/26.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRBaseRequstDataModel.h"
#import <objc/runtime.h>
#import "NSDictionary+Check.h"
#define SafeObj(obj) (obj==nil)?[NSNull null]:obj
@implementation HRBaseRequstDataModel
- (NSArray *)getAllPropertyNames       //获取类的所有属性名称
{
    u_int count;
    objc_property_t *properties  =class_copyPropertyList([self class], &count);
    NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i < count ; i++)
    {
        const char* propertyName =property_getName(properties[i]);
        [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
    }
    free(properties);
    return propertiesArray;
}

+ (id)modelBundingData:(NSDictionary *)dict{
    id model = [[self alloc] init];
    [model bundingData:dict];
    return model;
}

- (id)bundingData:(NSDictionary *)dict{          //绑定数据
    static Class oldClass;
    if ([self class]!=oldClass) {
        NSLog(@"   >>>>>>>  绑定模型 >>>>>>>>>> ： %@\n\n",[self class]);
        oldClass = [self class];
    }
    if (dict==nil) {
        return nil;
    }
    NSArray *propertyNames = [self getAllPropertyNames];
    for (NSString *key in propertyNames) {
        id value = [dict objectForKeyOrNil:key];
        if (value) {
            [self setValue:value forKey:key];   //使用KVC给属性赋值
        }
    }
    return self;
}


- (NSDictionary *)toDictionary{
    NSArray *propertyKeyArray = [self getAllPropertyNames];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for (NSString *key in propertyKeyArray) {
        id obj = SafeObj([self valueForKey:key]);
        //对象为空则不转换到Dictionary中
        if ((NSNull *)obj == [NSNull null]) {
            continue;
        }
        [dict setObject:obj forKey:key];
    }
    return dict;
}

- (NSDictionary *)toDictionaryWithItemPrompt:(NSString *)prompt  andIndex:(NSInteger)index{     //转化为带索引的描述型字典表示
    NSArray *propertyKeyArray = [self getAllPropertyNames];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for (NSString *key in propertyKeyArray) {
        id obj = SafeObj([self valueForKey:key]);
        //对象为空则不转换到Dictionary中
        if ((NSNull *)obj == [NSNull null]) {
            continue;
        }
        if(index>=0){
            NSString *key1 = [NSString stringWithFormat:@"%@[%ld].%@",prompt,index,key];
            [dict setObject:obj forKey:key1];
        }else{
            NSString *key1 = [NSString stringWithFormat:@"%@.%@",prompt,key];
            [dict setObject:obj forKey:key1];
        }
    }
    return dict;
}

- (void)clearData{          //清除对象的值
    //   DLog(@"%@",self);                   //输出调试信息
    NSArray *propertyNames = [self getAllPropertyNames];
    for (NSString *key in propertyNames) {
        [self setValue:nil forKey:key];   //使用KVC给属性赋值,清除对象的值
    }
}


- (NSString *)description               //类描述方法
{
    NSMutableString *desc = [NSMutableString string];
    [desc appendString:@"\n\n"];
    [desc appendFormat:@"Class name: %@\n", NSStringFromClass([self class])];
    NSArray *propertyNames = [self getAllPropertyNames];
    for (NSString *key in propertyNames) {
        [desc appendFormat: @"%@: %@\n", key, [self valueForKey:key]];
    }
    NSString *str = [NSString stringWithString:desc];
    return str;
}


#pragma -mark 对象归档协议<NSCoding>方法
- (void)encodeWithCoder:(NSCoder *)encoder {
    NSArray *propertyNames = [self getAllPropertyNames];
    for (NSString *key in propertyNames) {
        [encoder encodeObject:[self valueForKey:key] forKey:key];
    }
}

- (id)initWithCoder:(NSCoder *)decoder {
    NSArray *propertyNames = [self getAllPropertyNames];
    for (NSString *key in propertyNames) {
        [self setValue:[decoder decodeObjectForKey:key] forKey:key] ;
    }
    return self;
}

#pragma -mark 对象归档
- (void)archiverToFile:(NSString *)fileName{                        //对象归档保存
    NSString *fullPath = [self getDocumentsPath:fileName];
    [NSKeyedArchiver archiveRootObject:self toFile:fullPath];
}

- (id)unArchiverFromFile:(NSString *)fileName{                      //反归档对象
    NSString *fullPath = [self getDocumentsPath:fileName];
    if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]){
        HRBaseRequstDataModel *model = [NSKeyedUnarchiver unarchiveObjectWithFile: fullPath];
        return model;
    }else{
        return nil;
    }
}
#pragma -mark 辅助方法
- (NSString *)getDocumentsPath:(NSString *)fileName{          //获取文档目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath = [paths objectAtIndex:0];
    return [docPath stringByAppendingPathComponent:fileName];
}
@end
